import global from './config.js'
const wxPay = function(data) {
	//微信公众号支付
	function onBridgeReady() {
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest', {
				...data,
				// "appId": data.appid, //公众号名称，由商户传入     
				// "timeStamp": data.times, //时间戳，自1970年以来的秒数     
				// "nonceStr": data.nonce_str, //随机串     
				// "package": "prepay_id=u802345jgfjsdfgsdg888",
				// "signType": "RSA", //微信签名方式：     
				// "paySign": data.sign //微信签名 
			},
			function(res) {
				if (res.err_msg ==
					"get_brand_wcpay_request:ok") {
					// msg(res.msg)
				} // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。 
			}
		);
	}
	if (typeof WeixinJSBridge == "undefined") {
		if (document.addEventListener) {
			document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		} else if (document.attachEvent) {
			document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		}
	} else {
		onBridgeReady();
	}
}
const pay = function(pay) {

	// this.$tool.pay({orderInfo, provider:'alipay'})
	// uni.requestPayment({
	// 	provider:"",//alipay 支付宝  appleiap苹果   wxpay 微信
	// 	orderInfo: '',
	// 	success: res => {},
	// 	fail: () => {},
	// 	complete: () => {}
	// });
	// console.log(pay);
	// {
	// provider: '',
	// 	orderInfo: '',
	// }

	return new Promise((resolve, reject) => {
		uni.requestPayment({
			...pay,
			success: res2 => {
				console.log(res2);
				resolve(res2)
			},
			fail: (res2) => {
				console.log(res2);
				reject(res2)
			},
			complete: (res2) => {}
		});
	})
}
const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}
const uploadImg = () => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1, //最多可以选择的图片张数，默认9
			// sizeType: 'compressed', //	original 原图，compressed 压缩图，默认二者都有
			// sourceType: "", //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
			success(e) {
				let img = e.tempFilePaths[0]
				uni.uploadFile({
					header: {
						Authorization: uni.getStorageSync('token') || ''
					},
					url: global.baseUrl + '/master/upload/postUploadOneImg', //仅为示例，非真实的接口地址
					filePath: img,
					name: 'img',
					success: (res) => {
						res = JSON.parse(res.data)
						resolve(res)
					}
				});
			}
		})
	})
}
const copy = function(data, msg1 = '复制成功', msg2 = '复制失败') {
	uni.setClipboardData({
		data,
		success: function() {
			msg(msg1)
		},
		fail() {
			msg(msg2)
		}
	});
}

const jump = function(url) {
	if (!url) return msg('暂未开放')
	//保留当前页面，跳转到应用内的某个页面
	uni.navigateTo({
		url
	})
}
const sjump = function(url) {
	//跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
	uni.switchTab({
		url
	})
}
const rjump = function(url) {
	//关闭当前页面，跳转到应用内的某个页面
	uni.redirectTo({
		url
	})
}
const navBack = function(delta = 1, time = 0) {
	//返回页面
	let getPage = getCurrentPages()
	setTimeout(() => {
		if (getPage.length == 1) {
			uni.switchTab({
				url: '/pages/index/index'
			})
		} else {
			//关闭当前页面，返回上一页面或多级页面
			uni.navigateBack({
				delta
			})
		}
	}, time)
}
const reUrl = function(url) {
	//关闭所有页面，打开到应用内的某个页面
	uni.reLaunch({
		url
	})
}
const phone = (phoneNumber) => {
	//打电话
	console.log('打电话', phoneNumber);
	msg('打电话: '+phoneNumber)
	uni.makePhoneCall({
		phoneNumber,
	})
}
const lookImg = (urls, current = 0) => {
	// 预览图片
	// console.log(urls, current);
	uni.previewImage({
		urls,
		current,
		// indicator:true,
	});
}
const setTit = (title) => {
	uni.setNavigationBarTitle({
		title,
	})
}
const saveImg = (filePath) => {
	// #ifdef H5
	msg('长按图片保存')
	return
	// #endif
	uni.saveImageToPhotosAlbum({
		filePath,
		success(res) {
			msg('保存成功')
			console.log(errMsg);
		}
	})
}
const screenshot = () => {
	//app 绘制页面并保存图片
	// #ifdef APP-PLUS
	var pages = getCurrentPages();
	var page = pages[pages.length - 1];
	console.log("当前页" + pages.length - 1);
	var bitmap = null;
	var currentWebview = page.$getAppWebview();
	bitmap = new plus.nativeObj.Bitmap('amway_img');
	// 将webview内容绘制到Bitmap对象中  
	currentWebview.draw(bitmap, function() {
		console.log('截屏绘制图片成功');
		bitmap.save("_doc/a.jpg", {}, function(i) {
			console.log('保存图片成功：' + JSON.stringify(i));
			uni.saveImageToPhotosAlbum({
				filePath: i.target,
				success: function() {
					bitmap.clear(); //销毁Bitmap图片  
					uni.showToast({
						title: '保存图片成功',
						mask: false,
						duration: 1500
					});
				}
			});
		}, function(e) {
			console.log('保存图片失败：' + JSON.stringify(e));
		});
	}, function(e) {
		console.log('截屏绘制图片失败：' + JSON.stringify(e));
	});
	return
	// #endif
	uni.showToast({
		title: '请在app内使用该功能,或手动截屏',
		mask: false,
		duration: 1500,
		icon: 'error'
	});
}
const openLink = (href, mpTips = "链接已复制，请在浏览器打开") => {
	if (!href) return
	// #ifdef APP-PLUS
	plus.runtime.openURL(href) //调用第三方程序打开指定的URL
	// #endif
	// #ifdef H5
	window.open(href)
	// #endif
	// #ifdef MP
	uni.setClipboardData({
		data: href,
		success: () => {
			uni.hideToast();
			this.$nextTick(() => {
				msg(mpTips);
			})
		}
	});
	// #endif
}
let objToUrl = (url, query) => {
	url = url[0] === '/' ? url : `/${url}`
	for (let key in query) {
		if (url.indexOf('?') == -1) {
			url += '?' + key + '=' + query[key]
		} else {
			url += '&' + key + '=' + query[key]
		}
	}
	return url
}

function showModal(title = '', content,showCancel=true) { //二次确认筐
	return new Promise(function(resolve, err) {
		uni.showModal({
			title: title,
			content: content ?? ('确认' + title + '吗'),
			showCancel,
			success(res) {
				if (res.confirm) {
					resolve()
				} else {
					err('取消')
				}
			}
		})
	})
}
const refresh = () => { //刷新页面
	return new Promise((resolve, reject) => {
		let pages = getCurrentPages()
		let page = pages[pages.length - 1]
		let url = decodeURI(page.$page.fullPath)
		url = url[0] === '/' ? url : `/${url}`
		uni.redirectTo({
			url,
			success() {
				return resolve('刷新成功')
			},
			fail(res) {
				uni.reLaunch({
					url,
					success() {
						return resolve('刷新成功')
					},
					fail() {
						return reject('刷新失败')
					}
				})
			}
		})
	})
}

function splitArr(arr, size = 2) { //一维数组分割多个数组
	let aa = []
	// arr.map(item => { //渐进
	// 	let length = aa[aa.length - 1]?.length ||size
	// 	if (length == size) aa.push([])
	// 	aa[aa.length - 1].push(item)
	// })

	let page = arr.length / size
	if (arr.length % size) page = page + 1

	for (let i = 0; i < page; i++) {
		aa.push(arr.splice(0, 4))
	}
	return aa
}

export default {
	wxPay, //微信公众号支付
	pay,
	uploadImg,
	msg, //提示
	copy, //复制文字
	jump, //保留当前页面，跳转到应用内的某个页面
	sjump, //路由跳转 tabar  关闭非tabbar页面
	rjump, //路由跳转  关闭当前页面
	reUrl, //路由跳转  关闭所有页面
	navBack, //页面返回
	phone, //打电话
	lookImg, //查看图片
	setTit, //设置标题
	saveImg, //保存图片
	screenshot, //保存截图
	openLink, // 打开第三方链接链接
	objUrl: objToUrl, // 对象路由
	objToUrl, // 对象路由
	showModal,
	refresh,
	splitArr
}
